<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>首页</title>
    <style>
        /* 全局重置与基础样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, 
                         Helvetica, Arial, sans-serif;
        }
        
        :root {
            --primary-color: #1DBF7B;
            --text-color: #333;
            --white: #FFFFFF;
            --bg-color: #F7F8FA;
            --border-radius: 0.5rem;
        }
        
        body {
            margin: 0;
            padding: 0;
            color: var(--text-color);
            background-color: var(--bg-color);
           
        }
        
        /* 顶部状态栏 */
        .status-bar {
            background-color: var(--primary-color);
            height: 8.25rem;
            position: relative;
            color: var(--white);
            padding: 1rem;
        }
        
        /* 顶部标题居中 */
        .page-title {
            font-size: 1.0625rem;
            font-weight: bold;
            text-align: center;
            position: absolute;
            top: 33%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
        
        /* 用户信息区域 */
        .user-info {
            position: absolute;
            top: 4rem;
            left: 1rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        
        /* 头像样式 */
        .avatar {
            width: 3rem;
            height: 3rem;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid rgba(255, 255, 255, 0.8);
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
        }
        
        /* 用户名 */
        .username {
            font-size: 1rem;
            font-weight: 500;
        }
        
        /* 管理区域 */
        .management {
            position: absolute;
            top: 4.8rem;
            right: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        /*管理按钮*/
        .management-btn {
            font-size: 1rem;
            background: none;
            border: none;
            color: var(--white);
            cursor: pointer;/*鼠标箭头形象改变*/
        }
        
        /* 内容区域 */
        .content {
            padding: 1rem;
            margin-top: -1.5rem; /* 与状态栏重叠部分 */
        }
        
        /* 每日一练部分 */
        .daily-practice {
            background: var(--white);
            border-radius: var(--border-radius);
            padding: 1rem;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            margin-bottom: 1.5rem;
        }
       
        
        
        /* 任务列表 */
        .task-list {
            list-style: none;
        }
        
        .task-item {
            padding: 0.75rem 0;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            align-items: center;
        }
        
        .task-item:last-child {
            border-bottom: none;
        }
        
        .task-checkbox {
            margin-right: 0.75rem;
            width: 1.125rem;
            height: 1.125rem;
        }
        
        
        /* 底部导航 */
        nav {
            position:absolute;
            right:0;
            bottom: 0;
            left:0;
            width:100%;
            /*display: flex;*/
           /* justify-content: space-around;*/
            
            background-color:#ffffff;
            margin: 0; 
            padding: 0px;
            overflow: hidden;
            box-shadow: 0 0 4px rgba(0,0,0, 0.3);
            border: 1px solid rgba(0, 0, 0, 0.05)
            
        }
        /*底部导航栏--我的样式*/
        nav a {
            text-decoration: none;
            color: #000000;
           
            font-weight: 500;
            
            border-radius: var(--border-radius);
            margin:0px;
            background-color: rgb(255, 255, 255);
            padding: 0px 0px; 
            display: inline-block;
            width:50%;
            text-align: center;
            padding: 8px 0 8px;
            
        }
        
        nav img{
            background-color: #000000;
            width: 24px;
            height: 24px;
        }
        /*底部导航--首页样式*/
        nav a.active {
            display: inline-block;
            background-color: rgb(255, 255, 255);
            padding:6px 0;
            width:50%;
          
            
            width:50%;
            color: #1DBF7B;/*'首页'字体颜色*/
            padding: 4px 8px; 
            
        }
        
        /* 加载状态样式 */
        .loading {
            opacity: 0.6;
            pointer-events: none;
        }
        
        /* 进度条样式 */
        .progress-bar {
            width: 100%;
            height: 4px;
            background-color: #f0f0f0;
            border-radius: 2px;
            margin-top: 0.5rem;
            overflow: hidden;
        }
        
        .progress-fill {
            height: 100%;
            background-color: var(--primary-color);
            transition: width 0.3s ease;
        }
        
    </style>
</head>
<body>
    <!-- 顶部状态栏 -->
    <header class="status-bar">
        <h1 class="page-title">首页</h1>
        
        <!-- 用户信息 -->
        <div class="user-info">
            <img src="http://gips3.baidu.com/it/u=3886271102,3123389489&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=960" 
                 alt="用户头像" 
                 class="avatar"
                 id="userAvatar">
            <span class="username" id="userName">苟娅琳</span>
        </div>
        
        <!-- 管理区域 -->
        <div class="management">
            <button class="management-btn" id="managementBtn">管理</button>
            <button class="management-btn" id="menuBtn">⋮</button>
        </div>
    </header>
    
    <!-- 主要内容 -->
    <main class="content">
        <li>
        </li>
        <!-- 每日一练部分 -->
        <section class="daily-practice">
            <li class="task-item">
                    <input type="checkbox" id="task1" class="task-checkbox">
                    <label for="task1">每日一练</label>
                </li>
          </section>
         
       <section class="daily-practice">
            <ul class="task-list">
                <li class="task-item">
                    <input type="checkbox" id="task1" class="task-checkbox">
                    <label for="task1">历年真题</label>
                </li>
                <li class="task-item">
                    <input type="checkbox" id="task2" class="task-checkbox">
                    <label for="task2">模拟试题</label>
                </li>
                <li class="task-item">
                    <input type="checkbox" id="task3" class="task-checkbox">
                    <label for="task3">做题记录</label>
                </li>
            </ul>
        </section>
        
        <!-- 学习进度展示 -->
        <section class="daily-practice" id="progressSection" style="display: none;">
            <h3>学习进度</h3>
            <div class="progress-bar">
                <div class="progress-fill" id="progressFill"></div>
            </div>
            <p id="progressText">已完成 0/0 题</p>
        </section>
        
        

    </main>
    <!-- 底部导航 -->
        
        <nav>
            <a href="https:baidu.com" class="active"><img src=""><br>首页</a><a href="https:baidu.com"><img src=""><br>我的</a>
        </nav>

    <script>
        // 配置常量
        const API_CONFIG = {
            // 后端接口基础URL
            BASE_URL: 'http://localhost:8080/api',
            // 用户信息接口
            USER_INFO_URL: '/user/info',
            // 学习进度接口
            PROGRESS_URL: '/user/progress',
            // 任务完成接口
            TASK_COMPLETE_URL: '/task/complete',
            // 学习统计接口
            STATS_URL: '/user/stats'
        };

        // 用户状态管理
        const UserState = {
            isLoggedIn: false,
            openid: null,
            token: null,
            userInfo: null,
            studyProgress: null
        };

        // 工具函数：显示提示信息
        function showMessage(message, type = 'info') {
            console.log(`[${type.toUpperCase()}] ${message}`);
            // 可以在这里添加UI提示，比如toast组件
        }

        // 工具函数：获取URL参数
        function getUrlParameter(name) {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get(name);
        }

        // 工具函数：模拟网络延迟
        function delay(ms) {
            return new Promise(resolve => setTimeout(resolve, ms));
        }

        // 工具函数：验证用户登录状态
        function validateLogin() {
            const openid = getUrlParameter('openid');
            const token = getUrlParameter('token');
            
            if (!openid || !token) {
                showMessage('未检测到登录信息，请重新登录', 'error');
                // 跳转回登录页
                setTimeout(() => {
                    window.location.href = 'login.html';
                }, 2000);
                return false;
            }
            
            UserState.openid = openid;
            UserState.token = token;
            UserState.isLoggedIn = true;
            
            return true;
        }

        // 模拟API请求函数
        async function mockApiRequest(url, options = {}) {
            // 模拟网络错误
            if (Math.random() < 0.05) {
                throw new Error('网络连接失败');
            }
            
            // 模拟网络延迟
            await delay(Math.random() * 500 + 200);
            
            // 模拟不同的API响应
            if (url.includes('/user/info')) {
                return {
                    success: true,
                    data: {
                        id: 1,
                        openid: UserState.openid,
                        nickname: '苟娅琳',
                        avatar: 'http://gips3.baidu.com/it/u=3886271102,3123389489&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=960',
                        email: 'gouyalin@example.com',
                        phone: '138****8888',
                        lastLoginTime: new Date().toISOString()
                    },
                    message: '获取用户信息成功'
                };
            } else if (url.includes('/user/progress')) {
                return {
                    success: true,
                    data: {
                        openid: UserState.openid,
                        totalQuestions: 1250,
                        completedQuestions: 856,
                        accuracy: 0.78,
                        studyDays: 45,
                        currentStreak: 7,
                        lastStudyDate: new Date().toISOString()
                    },
                    message: '获取学习进度成功'
                };
            } else if (url.includes('/task/complete')) {
                const taskData = options.body ? JSON.parse(options.body) : {};
                return {
                    success: true,
                    data: {
                        taskId: taskData.taskId,
                        completed: true,
                        completedAt: new Date().toISOString(),
                        points: 10,
                        message: '任务完成！获得10积分'
                    },
                    message: '任务完成成功'
                };
            } else if (url.includes('/user/stats')) {
                return {
                    success: true,
                    data: {
                        openid: UserState.openid,
                        totalStudyTime: 12560, // 分钟
                        averageAccuracy: 0.78,
                        rank: 156,
                        totalUsers: 1250,
                        weeklyProgress: [65, 72, 68, 75, 80, 78, 82],
                        monthlyProgress: [320, 345, 378, 402]
                    },
                    message: '获取统计数据成功'
                };
            }
            
            // 默认响应
            return {
                success: false,
                message: '未知接口'
            };
        }

        // 获取用户信息
        async function fetchUserInfo() {
            try {
                showMessage('正在获取用户信息...', 'info');
                
                const response = await mockApiRequest(`${API_CONFIG.USER_INFO_URL}?openid=${UserState.openid}`, {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${UserState.token}`
                    }
                });
                
                if (response.success) {
                    UserState.userInfo = response.data;
                    updateUserInterface(response.data);
                    showMessage('用户信息获取成功', 'success');
                    return response.data;
                } else {
                    throw new Error(response.message || '获取用户信息失败');
                }
            } catch (error) {
                showMessage(`获取用户信息失败: ${error.message}`, 'error');
                throw error;
            }
        }

        // 获取学习进度
        async function fetchStudyProgress() {
            try {
                showMessage('正在获取学习进度...', 'info');
                
                const response = await mockApiRequest(`${API_CONFIG.PROGRESS_URL}?openid=${UserState.openid}`, {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${UserState.token}`
                    }
                });
                
                if (response.success) {
                    UserState.studyProgress = response.data;
                    updateProgressInterface(response.data);
                    showMessage('学习进度获取成功', 'success');
                    return response.data;
                } else {
                    throw new Error(response.message || '获取学习进度失败');
                }
            } catch (error) {
                showMessage(`获取学习进度失败: ${error.message}`, 'error');
                throw error;
            }
        }

        // 完成任务
        async function completeTask(taskId, taskName) {
            try {
                showMessage(`正在完成任务: ${taskName}...`, 'info');
                
                const taskData = {
                    openid: UserState.openid,
                    taskId: taskId,
                    taskName: taskName,
                    completedAt: new Date().toISOString()
                };
                
                const response = await mockApiRequest(API_CONFIG.TASK_COMPLETE_URL, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${UserState.token}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(taskData)
                });
                
                if (response.success) {
                    showMessage(`任务完成: ${response.data.message}`, 'success');
                    // 更新学习进度
                    await fetchStudyProgress();
                    return response.data;
                } else {
                    throw new Error(response.message || '任务完成失败');
                }
            } catch (error) {
                showMessage(`任务完成失败: ${error.message}`, 'error');
                throw error;
            }
        }

        // 获取学习统计
        async function fetchStudyStats() {
            try {
                showMessage('正在获取学习统计...', 'info');
                
                const response = await mockApiRequest(`${API_CONFIG.STATS_URL}?openid=${UserState.openid}`, {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${UserState.token}`
                    }
                });
                
                if (response.success) {
                    showMessage('学习统计获取成功', 'success');
                    console.log('学习统计数据:', response.data);
                    return response.data;
                } else {
                    throw new Error(response.message || '获取学习统计失败');
                }
            } catch (error) {
                showMessage(`获取学习统计失败: ${error.message}`, 'error');
                throw error;
            }
        }

        // 更新用户界面
        function updateUserInterface(userInfo) {
            const userNameElement = document.getElementById('userName');
            const userAvatarElement = document.getElementById('userAvatar');
            
            if (userNameElement && userInfo.nickname) {
                userNameElement.textContent = userInfo.nickname;
            }
            
            if (userAvatarElement && userInfo.avatar) {
                userAvatarElement.src = userInfo.avatar;
            }
        }

        // 更新进度界面
        function updateProgressInterface(progress) {
            const progressSection = document.getElementById('progressSection');
            const progressFill = document.getElementById('progressFill');
            const progressText = document.getElementById('progressText');
            
            if (progressSection) {
                progressSection.style.display = 'block';
            }
            
            if (progressFill && progressText) {
                const percentage = progress.totalQuestions > 0 
                    ? (progress.completedQuestions / progress.totalQuestions) * 100 
                    : 0;
                
                progressFill.style.width = `${percentage}%`;
                progressText.textContent = `已完成 ${progress.completedQuestions}/${progress.totalQuestions} 题 (${percentage.toFixed(1)}%)`;
            }
        }

        // 绑定任务复选框事件
        function bindTaskEvents() {
            const checkboxes = document.querySelectorAll('.task-checkbox');
            
            checkboxes.forEach((checkbox, index) => {
                checkbox.addEventListener('change', async function() {
                    if (this.checked) {
                        const taskName = this.nextElementSibling.textContent;
                        const taskId = `task_${index + 1}`;
                        
                        try {
                            await completeTask(taskId, taskName);
                        } catch (error) {
                            // 如果任务完成失败，取消勾选
                            this.checked = false;
                        }
                    }
                });
            });
        }

        // 绑定管理按钮事件
        function bindManagementEvents() {
            const managementBtn = document.getElementById('managementBtn');
            const menuBtn = document.getElementById('menuBtn');
            
            if (managementBtn) {
                managementBtn.addEventListener('click', async function() {
                    showMessage('正在获取学习统计...', 'info');
                    try {
                        await fetchStudyStats();
                    } catch (error) {
                        showMessage('获取统计信息失败', 'error');
                    }
                });
            }
            
            if (menuBtn) {
                menuBtn.addEventListener('click', function() {
                    showMessage('菜单功能开发中...', 'info');
                });
            }
        }

        // 页面初始化
        async function initializePage() {
            try {
                // 1. 验证登录状态
                if (!validateLogin()) {
                    return;
                }
                
                // 2. 获取用户信息
                await fetchUserInfo();
                
                // 3. 获取学习进度
                await fetchStudyProgress();
                
                // 4. 绑定事件
                bindTaskEvents();
                bindManagementEvents();
                
                showMessage('页面初始化完成', 'success');
                
            } catch (error) {
                showMessage(`页面初始化失败: ${error.message}`, 'error');
            }
        }

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 开始页面初始化
            initializePage();
        });

        // 导出用户状态和API配置，供其他页面使用
        window.UserState = UserState;
        window.API_CONFIG = API_CONFIG;
        window.mockApiRequest = mockApiRequest;
    </script>
</body>
</html>